package com.luobu.javaee.service;

import com.luobu.javaee.dao.DocumentEsRepository;
import com.luobu.javaee.domain.DocumentSearch;
import com.luobu.javaee.domain.dto.DocumentDto;
import com.luobu.javaee.domain.dto.DocumentResDto;
import com.luobu.javaee.util.SearchUtil;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DocumentElasticSearchService {

    @Autowired
    private DocumentEsRepository documentEsRepository;
    public List<DocumentResDto> findDocByDocName(String docName){
        List<DocumentSearch> searchRes = documentEsRepository.findByDocNameCustom(docName);
        return getDocumentResDtos(searchRes);
    }

    /*
    根据用户id和文档名称查询文档
    * */
    public List<DocumentResDto> findDocByDocNameAndUserId(String docName, Long userId){
        List<DocumentSearch> searchRes = documentEsRepository.findByDocNameAndUserId(docName, userId);
        return getDocumentResDtos(searchRes);
    }

    /*
    *根据docSearch构建docRes
    * */
    private List<DocumentResDto> getDocumentResDtos(List<DocumentSearch> searchRes) {
        List<DocumentResDto> documentResDtoList = new ArrayList<>();
        for (DocumentSearch documentSearch : searchRes){
            DocumentResDto documentResDto = new DocumentResDto();
            documentResDto.setDocName(documentSearch.getDocName());
            documentResDto.setDocId(documentSearch.getDocId());
            documentResDtoList.add(documentResDto);
        }
        return documentResDtoList;
    }

    /*
    * 上传记录
    * */
    public void upload(DocumentDto documentDto){
        DocumentSearch documentSearch = SearchUtil.buildDocSearchFromDocDto(documentDto);
        documentEsRepository.save(documentSearch);
    }

    /*
    * 根据用户名和文档名删除记录
    * */
    public void deleteByUidAndDocName(Long userId, String docName){
        documentEsRepository.deleteByUserIdAndDocName(userId, docName);
    }

    /*
     * 根据用户名和文档名删除记录
     * */
    public void deleteByDocId(Long docId){
        documentEsRepository.deleteByDocId(docId);
    }

    /*
    * 根据关键词列表查询相关记录
    * */
    public List<DocumentResDto> multiKeywordsSearch(List<String> keywords, Long userId){
        List<DocumentSearch> searchRes = documentEsRepository.findByUserIdAndDocNameIn(userId, keywords);
        return getDocumentResDtos(searchRes);
    }

    public List<DocumentResDto> searchInArchive(String keyword, Long archiveId) {
        List<DocumentSearch> searchRes = documentEsRepository.matchDocsInArchive(keyword, archiveId);
        return getDocumentResDtos(searchRes);
    }
}
